<template>
  <div class="ShoppingTrolley-component">
    <el-card class="box-card el-mai-box">
      <MyHeader background="#1d7bff" title="购物车案例" color="#fff"></MyHeader>
      <!-- 循环选人每一个商品 -->
      <MyGoods
        v-for="item in list"
        :key="item.id"
        :id="item.id"
        :count="item.goods_count"
        :state="item.goods_state"
        :price="item.goods_price"
        :img="item.goods_img"
        :title="item.goods_name"
        @change-satae="changeGoods(item, $event)"
      >
        <MyCount :sum="item"></MyCount>
      </MyGoods>
      <MyFooter
        :FouterSum="FouterSum"
        :FouterState="FouterState"
        :FouterAll="FouterAll"
        @changesatae="GoosState"
      ></MyFooter>
    </el-card>
  </div>
</template>

<script>
import MyCount from '@/components/Day/Day4/ShoppingTrolley/MyCount.vue'
import MyFooter from '@/components/Day/Day4/ShoppingTrolley/MyFooter.vue'
import MyGoods from '@/components/Day/Day4/ShoppingTrolley/MyGoods.vue'
import MyHeader from '@/components/Day/Day4/ShoppingTrolley/MyHeader.vue'
// 导入创建的 小 axios
import axios from '@/views/Day/Day4/views/ShoppingTrolley/axios.js'

export default {
  components: {
    MyCount,
    MyFooter,
    MyGoods,
    MyHeader
  },
  data() {
    return {
      list: []
    }
  },
  async created() {
    const { data: res } = await axios({ url: '/api/cart' })
    this.list = res.list
  },
  computed: {
    // 计算总价格
    FouterSum() {
      return this.list
        .filter(item => item.goods_state)
        .reduce((acc, val) => (acc += val.goods_count * val.goods_price), 0)
    },
    // 计算全选状态
    FouterState() {
      return this.list.every(item => item.goods_state)
    },
    // 计算以勾上的总条数
    FouterAll() {
      return this.list
        .filter(item => item.goods_state)
        .reduce((acc, val) => (acc += val.goods_count), 0)
    }
  },
  methods: {
    // 根据MyFooter传过来的状态 来渲染全选的状来改变小选状态
    GoosState(val) {
      return this.list.forEach(item => (item.goods_state = val))
    },
    // MyGoods 传过来的状态
    changeGoods(v, e) {
      v.goods_state = e
    }
  }
}
</script>

<style lang="less" scoped>
.ShoppingTrolley-component {
  box-sizing: border-box;
  position: relative;
  left: 50%;
  transform: translateX(-50%);
  width: 70%;
  height: 1000px;
  padding: 25px 0;
  .box-card {
    height: 100% !important;
    overflow: scroll !important;
  }
}
</style>
